package com.sand.service.Imp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sand.dao.IBaseDao;
import com.sand.entity.*;
import com.sand.service.IMessageService;
import com.sand.util.PageModel;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;

@Service(value = "messageService")
public class MessageServiceImp implements IMessageService {
/**
 *
 *
 * @author <achao1441470436@gmail.com>
 * @since 2021/12/5/005 3:23
 */
    //Dao层接口
    @Resource(name = "baseDao")
    private IBaseDao baseDao;

    //根据用户查询所有聊天对象
    @Override
    public List<HashMap<String, Object>> queryMessageByUser(int id,int isUser) {
        List<HashMap<String,Object>> list;
        switch (isUser){
            case 0:
                list = baseDao.queryObject("select new Map(" +
                    "t1.lastChatTime as time,t1.lastChatMessage as lastmsg,t2.name as name,t2.avater as avater," +
                        "t2.userId as userid,t1.rid as rid,t1.landlordId as landlordId,t2.avater as avater)" +
                    "from MessageEntity t1 inner join UserdetailsEntity t2 on t1.landlordId=t2.userId " +
                    "where t1.userId=?0", id);
                break;
            case 1:
                list = baseDao.queryObject("select new Map(" +
                    "t1.lastChatTime as time,t1.lastChatMessage as lastmsg,t2.name as name,t2.avater as avater," +
                        "t2.userId as userid,t1.rid as rid,t1.landlordId as landlordId,t2.avater as avater)" +
                    "from MessageEntity t1 inner join UserdetailsEntity t2 on t1.userId=t2.userId " +
                    "where t1.landlordId=?0", id);
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + isUser);
        }
        return list;
    }
    //根据id查询聊天详细信息，包括聊天记录
    @Override
    public HashMap<String, Object> queryMessageById(int id) {
        List<HashMap<String, Object>> list = baseDao.queryObject(" select new Map(" +
                "t1.rid as rid,t1.userId as userId,t1.landlordId as landlordId,t2.name as userName," +
                "t1.lastChatTime as lastChatTime,t1.lastChatMessage as lastChatMessage,t2.avater as userAvater) " +
                "from MessageEntity t1,UserdetailsEntity t2 where t1.userId=t2.userId and t1.rid=?0", id);
        HashMap<String, Object> map = list.get(0);
        List<HashMap<String,Object>> list1 = baseDao.queryObject("select new Map(t1.name as name,t1.avater as avater) from UserdetailsEntity t1 where t1.userId=?0", Integer.parseInt(map.get("landlordId").toString()));
        map.put("name",list1.get(0).get("name"));
        map.put("avater",list1.get(0).get("avater"));
        List list2 = baseDao.queryObject("select t1 from MessagedetailsEntity t1 inner join MessageEntity t2 on t1.messageId=t2.rid where t2.rid=?0", id);
        map.put("list",list2);

        return map;
    }
    //分页查询聊天
    @Override
    public PageModel<HashMap<String, Object>> queryMessageLimit(int limit, int page, String condition) {
        PageModel<HashMap<String, Object>> pm = new PageModel<HashMap<String, Object>>();

        //计算开始位置
        int begin=(page-1)*limit;
        //创建查询对象
        DetachedCriteria dc = DetachedCriteria.forClass(MessageEntity.class);
        //添加模糊查询条件
        if(condition!=null){
            JSONObject obj = JSON.parseObject(condition);
            if(obj.get("userName")!=null && !"".equals(obj.get("userName"))){
                List list = baseDao.queryObject("select t.rid from UserdetailsEntity t1 where t1.name like '%"+obj.get("userName").toString()+"%'");
                dc.add(Restrictions.in("userId",list));
            }
            if(obj.get("name")!=null && !"".equals(obj.get("name"))){
                List list = baseDao.queryObject("select t.rid from UserdetailsEntity t1 where t1.name like '%"+obj.get("name").toString()+"%'");
                dc.add(Restrictions.in("landlordId",list));
            }
        }

        List<Long> list1 = baseDao.queryObjectCommon(dc.setProjection(Projections.rowCount()));
        dc.setProjection(null);
        dc.setProjection(Projections.property("rid"));
        dc.addOrder(Order.desc("rid"));
        List list = baseDao.queryObjectLimit(dc, begin, limit);
        long i=list1.get(0);
        int count= (int) i;

        List<HashMap<String, Object>> list2 = baseDao.queryObject(" select new Map(" +
                "t1.rid as rid,t1.landlordId as landlordId,t2.name as userName,t1.lastChatTime as lastChatTime,t1.lastChatMessage as lastChatMessage) " +
                "from MessageEntity t1,UserdetailsEntity t2 where t1.userId=t2.userId and t1.rid in (?0)", list);
        for (HashMap<String, Object> map : list2) {
            List<String> list3 = baseDao.queryObject("select t1.name from UserdetailsEntity t1 where t1.userId=?0", Integer.parseInt(map.get("landlordId").toString()));
            map.put("name",list3.get(0));
        }

        pm.setList(list2);
        pm.setPageNo(page);
        pm.setPageSize(limit);
        pm.setPagecount(count);
        return pm;
    }
    //根据用户id和房东id查询会话id
    @Override
    public int queryMessageByCondition(int userId, int landId) {
        List<Integer> list = baseDao.queryObject("select t1.rid from MessageEntity t1 where t1.userId=?0 and t1.landlordId=?1", userId, landId);
        return list.get(0);
    }

    //添加聊天对象
    @Override
    public boolean addMessage(String data) {
        //创建时间
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        if(data!=null){
            MessageEntity msg = JSON.parseObject(data, MessageEntity.class);
            msg.setLastChatTime(timestamp);
            msg.setLastChatMessage("我发起了在线聊天,一起交流吧！");
            boolean bln = baseDao.addObject(msg);
            if(bln)return true;
        }
        return false;
    }

    //添加聊天记录
    @Override
    public boolean addMessagedetails(String data) {
        //创建时间
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        if(data!=null){
            MessagedetailsEntity msgd = JSON.parseObject(data, MessagedetailsEntity.class);
            msgd.setTime(timestamp);
            boolean bln = baseDao.addObject(msgd);
            if(bln){
                List<MessageEntity> list = baseDao.queryObject("from MessageEntity t1 where t1.rid=?0", msgd.getMessageId());
                MessageEntity msg = list.get(0);
                msg.setLastChatTime(msgd.getTime());
                msg.setLastChatMessage(msgd.getContent());
                boolean b = baseDao.updateObject(msg);
                if(b){
                    return true;
                }
            }
        }
        return false;
    }
    //删除聊天
    @Override
    public boolean delMessage(String data) {
        if(data!=null){
            List<MessageEntity> list = JSON.parseArray(data, MessageEntity.class);
            boolean bln = baseDao.delAllObject(list);
            if(bln)return true;
        }
        return false;
    }
    //删除聊天记录
    @Override
    public boolean delMessagedetails(int id) {
        MessagedetailsEntity msg = new MessagedetailsEntity();
        msg.setRid(id);
        boolean bln = baseDao.delObject(msg);
        if(bln)return true;
        return false;
    }



    //++++++++++++++++++++++++（lyl service）+++++++++++++++++++++++++++




}
